﻿namespace MiniApiProject.Endpoints.Internal;

public static class EndpointExtensions
{

    public static void AddEndpoints<T>(this IServiceCollection services, IConfiguration configuration)
    {
        AddEndpoints(services, typeof(T), configuration);
    }
    public static void AddEndpoints(this IServiceCollection services, Type type, IConfiguration configuration)
    {
        BaseEndpoints(type, nameof(IEndpoints.AddServices), [services, configuration]);
    }

    public static void UseEndpoints<T>(this IApplicationBuilder app)
    {
        UseEndpoints(app, typeof(T));
    }
    public static void UseEndpoints(this IApplicationBuilder app, Type type)
    {
        BaseEndpoints(type, nameof(IEndpoints.DefineEndpoints), [app]);
    }

    public static void BaseEndpoints(Type t, string funcName, object[] args)
    {
        var types = t.Assembly.GetTypes().Where(x => !x.IsInterface && !x.IsAbstract && typeof(IEndpoints).IsAssignableFrom(x));

        foreach (var type in types)
        {
            type.GetMethod(funcName)!.Invoke(null, args);
        }
    }
}
